﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GMS.MainClasses;
using GMS.ServiceFunctions.Data;
using System.IO;
using System.Data.SqlClient;
using System.Reflection;
using System.Collections;


namespace GMS.ViewForms
{
    public partial class AddEditForm : ChildForms
    {
        BindingSource bsForms = new BindingSource();
        private Int32 idForm;
        public Int32 IdForm
        {
            get { return idForm; }
            set { idForm = value; }
        }
        public enum EditMode
        { 
            Добавление,
            Редактирование,
            Удаление
        }
        private EditMode formMode;
        public EditMode FormMode
        {
            get { return formMode; }
            set { formMode = value; }
        }
        public AddEditForm(EditMode FormMode)
        {
            InitializeComponent();
            this.FormMode = FormMode;

            StoredProcedures = new String[5];
            StoredProcedures[0] = "[AddForm]";
            StoredProcedures[1] = "[EditForm]";
            StoredProcedures[2] = "[DeleteForm]";
            StoredProcedures[3] = "[SelectForms]";
            StoredProcedures[4] = "[AddFormSP]";

            if (FormMode == EditMode.Добавление)
                Text = "Добавление формы";
            if (FormMode == EditMode.Редактирование)
                Text = "Редактирвание формы";
            if (FormMode == EditMode.Удаление)
            {
                Text = "Удаление формы";
                button1.Enabled = false;
                textBox1.ReadOnly = true;
            }
        }
        private Type[] types;
        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "dll files (*.dll)|*.dll";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try 
                {
                    textBox2.Text = Path.GetFileName(openFileDialog1.FileName).ToString();
                    System.Reflection.Assembly Assembly = System.Reflection.Assembly.LoadFrom(openFileDialog1.FileName.ToString());
                    types = Assembly.GetTypes();
                    textBox3.Text = types[0].FullName;

                    if (types.Length > 1)
                    {
                        button2.Enabled = true;
                        button3.Enabled = true;
                    }
                }
                catch (Exception ex)
                { MessageBox.Show("Невозможно прочиатать файл. Ошибка - "+ex.ToString(),"Ошибка!!!",MessageBoxButtons.OK,MessageBoxIcon.Error); }
            }
            try
            {
                listBox1.Items.Clear();
                foreach (String S in GetSP(types))
                    listBox1.Items.Add(S);
                
            }
            catch { }
        }
        Int32 i = 0;
        private void button3_Click(object sender, EventArgs e)
        {
            if (i < types.Length-1)
                i = i + 1;
            textBox3.Text =types[i].FullName;
            try { GetSP(types); }
            catch { }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (i > 0)
                i = i - 1;
            textBox3.Text =types[i].FullName;
            try { GetSP(types); }
            catch { }
        }

        private void AddEditForm_Load(object sender, EventArgs e)
        {
            bsForms.DataSource = MRF.ReturnDataSetDB(ConnectionString, StoredProcedures[3]);
            bsForms.DataMember = "table";

            bsForms.Filter = "IdForm = "+IdForm;

            if (FormMode == EditMode.Редактирование || FormMode == EditMode.Удаление)
            {
                textBox1.DataBindings.Add("Text", bsForms, "Название формы");
                textBox2.DataBindings.Add("Text", bsForms, "Сборка");
                textBox3.DataBindings.Add("Text", bsForms, "Пространство имен");
            }

        }

        private void acceptButton1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim() == String.Empty)
            {
                MessageBox.Show("Пустое название формы!!! Операция отменена!!!", "Ошибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (FormMode == EditMode.Добавление)
            {
                using (SqlConnection SC = new SqlConnection(ConnectionString))
                {
                    SC.Open();
                    SqlTransaction TA = SC.BeginTransaction();
                    try
                    {
                        Int32 i = Convert.ToInt32(MRF.ExecuteSqlCommandScalar(StoredProcedures[0] + " '" + textBox1.Text.Trim() + "','" + textBox2.Text.Trim() + "','" + textBox3.Text.Trim() + "'", ConnectionString, TA, SC));
                        if (GetSP(types).Length!= 0)
                        {
                            foreach (String s in GetSP(types))
                            {
                                MRF.ExecuteSqlCommand(StoredProcedures[4] + " " + i + ",'" + s + "'", ConnectionString, TA, SC);
                            }
                        }
                        TA.Commit();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString(), "Ошибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    SC.Close();
                }

            }
            if (FormMode == EditMode.Редактирование)
            {
                MRF.ExecuteSqlCommand(StoredProcedures[1]+" " +IdForm+",'"+textBox1.Text.Trim()+"','"+textBox2.Text.Trim()+"','"+textBox3.Text.Trim()+"'", ConnectionString);
            }
            if (FormMode == EditMode.Удаление)
            {
                MRF.ExecuteSqlCommand(StoredProcedures[2]+ " "+ IdForm, ConnectionString);
            }
        }
        

        String[] GetSP(Type[] Types)
        {
            String[] SP = null;
            ArrayList arr = new ArrayList();
            foreach(Type T in Types )
            {
                PropertyInfo[] P = T.GetProperties();
                Int32 SPCounter = 0;
                for (Int32 t = 0; t <= P.Length - 1; t++)
                {
                    if (P[t].Name == "StoredProcedures")
                        SPCounter = SPCounter + 1;
                }
                if (SPCounter != 0)
                {
                    foreach (PropertyInfo PI in P)
                    {
                        if (PI.Name == "StoredProcedures")
                        {
                            object obj = new object();

                            try
                            {
                                obj = Activator.CreateInstance(T);
                            }
                            catch (MissingMethodException)
                            {
                                obj = Activator.CreateInstance(T, (object)null);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.ToString());
                                return null;
                            }

                            GMS.MainClasses.ChildForms CF = (GMS.MainClasses.ChildForms)obj;
                            String[] SoP = new String[CF.StoredProcedures.Length];

                            foreach (String s in CF.StoredProcedures)
                                arr.Add(s);
                        }
                    }
                }
            }
            arr.Sort();
            String ss = arr[0].ToString();
            for (int g = 1; g < arr.Count; g++)
            {
                if (ss == arr[g].ToString())
                {
                    arr.RemoveAt(g);
                    g = g - 1;
                }
                ss = arr[g].ToString();
            }
            SP = new String[arr.Count];
            arr.CopyTo(SP);
            return SP;
        }

        private void button4_Click(object sender, EventArgs e)
        {

        }
    }
}
